<template>
  <div class="amapsBox">
  	<div class="btnBox">
  		<div class="creatPoly" @click="creatPolygon">创建轮廓</div>
  		<!--<div class="creatPoly" >编辑轮廓</div>-->
  		<div class="creatPoly" @click="closeEditPolygon">编辑完成</div>
  	</div>
  	<div class="tips">创建轮廓或修改轮廓后请点击右上角<span>“编辑完成”</span>按钮</div>
  	<div class="amaps" id="amaps"></div>
  </div>
</template>

<script>
export default {
//props: {
//  defaultAreaLine:{ type: Array },
//},
  props: {
    defaultAreaLine: {
      type: Array,
      default: () => []
    },
  },
  watch:{
	defaultAreaLine	: {
		deep: true,
     immediate: true,
	   handler (newVal,oldVal) {
	    if (newVal != oldVal) {
    		if(this.beginPoints.length>0)this.map.clearMap();
				this.editRegion = newVal;
        this.init();
	    }
	   }　  
	 },
  },
  data(){
  	return{
//		polyEditor:null,
  		center: [116.475334, 39.997534],
      zoom: 16.8,
      map:null,
      editRegion:[[116.475334, 39.997534], [116.476627, 39.998315], [116.478603, 39.99879], [116.478529, 40.000296], [116.475082, 40.000151], [116.473421, 39.998717]],
      polygon:null,//创建的多边形
  		clickListener:null,
  		beginPoints:[],
  		beginMarks:[],
  		beginNum:0,
  		polygonEditor:null,
  		resPolygon:[],
  		resNum:0,
//			editRegion:[],//传递的数据
  	}
  },
  mounted(){
		this.creatMap();
    this.init();
  },
  methods:{
  	//创建
  	creatPolygon(){
  		this.editRegion = [];
      if(this.polygon)this.map.remove(this.polygon)
      if(this.beginPoints.length>0)this.map.remove(this.beginPoints)
      
      if(this.polygonEditor!=null){
      	this.polygonEditor.close()
      	this.map.remove(this.polygonEditor)
      }
  	},
  	creatMap(){
  		this.map = new AMap.Map("amaps", {
	        resizeEnable: true,
	        center: [116.403322, 39.900255],//地图中心点
	        zoom: this.zoom
	    });
//    console.log("creat map",this.map);    
  	},
  	async init(){
//      await this.creatMap();
        this.beginPoints = [];
        this.beginMarks = [];
        this.beginNum = 0;
        this.polygon = null;
        this.polygonEditor = null;
        if(this.editRegion.length>0){
//          this.beginPoints = this.JsonToArray(this.editRegion);
            this.beginPoints = this.editRegion;
            // console.log("66666666111",this.beginPoints)
            this.polygon = this.createPolygon(this.beginPoints);      
            this.polygonEditor = this.createEditor(this.polygon);
//          console.log("this.map",this.map);
            this.map.setFitView();
//          console.log("查看是否会走这里")
        }else{
//      	console.log("66666666")
          this.clickListener = AMap.event.addListener(this.map, "click", this.mapOnClick);
        }
    },
    mapOnClick(e) {
        this.beginMarks.push(this.addMarker(e.lnglat));
//      console.log(e.lnglat);
        this.beginPoints.push(e.lnglat);
        this.beginNum ++ ;
        if(this.beginNum == 3){
            AMap.event.removeListener(this.clickListener);
            this.polygon = this.createPolygon(this.beginPoints);
            this.polygonEditor = this.createEditor(this.polygon);
            this.clearMarks();
        }
    },
    createPolygon(arr){
//  	console.log("arr",arr)
			let that = this;
	    var polygon = new AMap.Polygon({
	        map: that.map,
	        path: arr,
	        strokeColor: "#0000ff",
	        strokeOpacity: 1,
	        strokeWeight: 3,
	        fillColor: "#f5deb3",
	        fillOpacity: 0.35
	    });
	    return polygon;
    },
    createEditor(polygon){
        var polygonEditor = new AMap.PolyEditor(this.map, polygon);
         // console.log(polygonEditor,"正常")
        polygonEditor.open();
        AMap.event.addListener(polygonEditor,'end',this.polygonEnd);
//      console.log("polygonEditor周到：",polygonEditor)
        return polygonEditor;
    },
    closeEditPolygon(){
        if(!this.polygonEditor){
            console.log('未获取到地图');
            return false;
        }
        //polygonEditor.close();//关闭编辑状态
        var FenceRegion = [];
        if(!this.beginPoints){
            console.log('未获取到坐标');
            return false;
        }
        this.beginPoints.forEach(function(item,index){
            var lng = parseFloat(item['lng']);//经
            var lat = parseFloat(item['lat']);//纬
            FenceRegion.push([lng,lat]);
        });
        var newRegion = this.ObjectToJson(FenceRegion);
        console.log("newRegion",newRegion);
        this.$emit('getLine', newRegion);
    },
    polygonEnd(res){
//  	console.log("res",res)
        this.resPolygon.push(res.target);
        
        this.resNum++;
        this.init();
    },
    clearMarks(){
        this.map.remove(this.beginMarks);
    },
    JsonToArray(obj){
//      var arr = JSON.parse(json);
        let arr = obj;
        var res = [];
        for (var i = 0; i < arr.length; i++) {
            var line = [];
            line.push(arr[i].lng);
            line.push(arr[i].lat);
//          console.log("每一个：",line)
            res.push(line);
        };
//      console.log("我的结果是：",res)
        return res;
    },
    addMarker(lnglat) {
        var marker = new AMap.Marker({
            // icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
            position: lnglat
        });
        marker.setMap(this.map);
        return marker;
    },
    ObjectToJson(arr){
        if(!arr.length) return null;
        var i = 0;
        let len = arr.length,
        array = [];
        for(;i<len;i++){
            array.push([arr[i][0],arr[i][1]]);
        }
        return array;
    }
    

  }
}
</script>

<style scoped>
 .amapsBox{position:relative;width: 100%;}
 .amaps {
    width: 100%;
    height: 530px;
  }
  .tips{position:absolute;top:-28px;right:0;z-index:130;color:#4355FA;width:100%;text-align:right;}
  .tips span{color:red;}
  .btnBox{
  	position:absolute;top:0;right:0;z-index:130;padding:15px 15px 0;line-height:30px;
  	background-color:#fff;color:#4355FA;overflow:hidden;border-radius:15px 0 0 15px;
  	box-shadow:0 3px 5px rgba(0,0,0,.3);
  }
  .creatPoly{
  	border:1px solid #4355FA;
  	margin-bottom:15px;padding:0 15px;overflow:hidden;border-radius:30px;
  	font-size:14px;
  }
  .creatPoly:hover{color:#fff;background-color:#4355FA;cursor:pointer;}
  .creatPoly:last-of-type{color:#FF5220;border-color:#FF5220;}
  .creatPoly:last-of-type:hover{background-color:#FF5220;color:#fff;}
</style>
